package service

import (
	"blog/internal/model"
	"blog/internal/repository"
	"context"
)

type ArticleTagRelationService interface {
	GetTagIDsByArticleID(ctx context.Context, articleID uint) ([]uint, error)
	CreateRelations(ctx context.Context, articleID uint, tagIDs []uint) error
	DeleteRelationsByArticleID(ctx context.Context, articleID uint) error
	GetArticleIDsByTagID(ctx context.Context, tagID uint) ([]uint, error)
}

func NewArticleTagRelationService(
	service *Service,
	articleTagRelationRepository repository.ArticleTagRelationRepository,
) ArticleTagRelationService {
	return &articleTagRelationService{
		Service:      service,
		relationRepo: articleTagRelationRepository,
	}
}

type articleTagRelationService struct {
	*Service
	relationRepo repository.ArticleTagRelationRepository
}

func (s *articleTagRelationService) GetArticleIDsByTagID(ctx context.Context, tagID uint) ([]uint, error) {
	var ids []uint
	err := s.relationRepo.GetArticleIDsByTagID(ctx, tagID, &ids)
	if err != nil {
		return nil, err
	}
	return ids, nil
}

func (s *articleTagRelationService) GetTagIDsByArticleID(ctx context.Context, articleID uint) ([]uint, error) {
	return s.relationRepo.GetTagIDsByArticleID(ctx, articleID)
}
func (s *articleTagRelationService) CreateRelations(ctx context.Context, articleID uint, tagIDs []uint) error {
	for _, tagID := range tagIDs {
		relation := &model.ArticleTagRelation{
			ArticleID: articleID,
			TagID:     tagID,
		}
		if err := s.relationRepo.CreateRelation(ctx, relation); err != nil {
			return err
		}
	}
	return nil
}

func (s *articleTagRelationService) DeleteRelationsByArticleID(ctx context.Context, articleID uint) error {
	return s.relationRepo.DeleteRelationsByArticleID(ctx, articleID)
}
